package com.situ.mall.controller;

import com.situ.mall.constant.RedisConstants;
import com.situ.mall.pojo.entity.Product;
import com.situ.mall.pojo.query.ProductQuery;
import com.situ.mall.service.IProductService;
import com.situ.mall.util.PageResult;
import com.situ.mall.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/list")
    public PageResult list(ProductQuery productQuery) {
        return productService.list(productQuery);
    }

    @RequestMapping("/add")
    public Result add(Product product) {
        productService.add(product);
        //将Product中真正使用的图片保存在Redis中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, product.getMainImage());
        return Result.ok("添加成功");
    }


    @RequestMapping("/selectById")
    public Result selectById(Integer id) {
        Product product = productService.selectById(id);
        return Result.ok(product);
    }

    @RequestMapping("/update")
    public Result update(Product product) {
        productService.update(product);
        //将Product中真正使用的图片保存在Redis中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, product.getMainImage());
        return Result.ok("更新成功");
    }

    @RequestMapping("/deleteAll")
    public Result deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        String[] ids = req.getParameterValues("ids[]");
        productService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id) {
        productService.deleteById(id);
        return Result.ok("删除成功");
    }

}